<template>
<div v-wechat-title="$route.meta.title"></div>
  <Header />
    <div id="card" :style="{ backgroundImage: 'url(' + background_image + ')' }">
     <el-card class="box-card" shadow="hover">
        <div class="icon-card"><el-image
            style="width: 50px; height: 50px"
            :src="icon_img"
            :fit="scale-down"></el-image>
            <span id="login-title">创建新账号</span>
        </div>
        <a-form
            ref="formRef"
            :model="formState"
            name="login"
            :rules="rules"
            v-bind="layout"
            class="login-form"
            @finish="handleFinish"
            @validate="handleValidate"
            @finishFailed="handleFinishFailed"
        >
            <a-form-item has-feedback label="昵称" name="name">
              <a-input v-model:value="formState.name" autocomplete="off">
              <template #prefix>
                  <UserOutlined class="site-form-item-icon" />
              </template>
              </a-input>
            </a-form-item>

            <a-form-item has-feedback label="手机号" name="telephone">
                <a-input v-model:value="formState.telephone" autocomplete="off">
                <template #prefix>
                    <PhoneOutlined class="site-form-item-icon" />
                </template>
                </a-input>
            </a-form-item>

            <a-form-item has-feedback label="密码" name="password">
                <a-input-password v-model:value="formState.password" autocomplete="off">
                <template #prefix>
                    <LockOutlined class="site-form-item-icon" />
                </template>
                </a-input-password>
            </a-form-item>

            <a-form-item has-feedback label="确认密码" name="password2">
                <a-input-password v-model:value="formState.password2" autocomplete="off">
                <template #prefix>
                    <LockOutlined class="site-form-item-icon" />
                </template>
                </a-input-password>
            </a-form-item>

            <a-form-item has-feedback label="验证码" name="verifycode">
                <a-input v-model:value="formState.verifycode" autocomplete="off">
                <template #prefix>
                    <CheckCircleOutlined class="site-form-item-icon" />
                </template>
                </a-input>
            </a-form-item>

            <a-form-item :wrapper-col="{ offset: 3, span: 16 }">
                <div class="identifybox">
                    <div @click="refreshCode">
                        <s-identify :identifyCode="identifyCode"></s-identify>
                    </div>
                    <span @click="refreshCode" class="text">看不清，换一张<sync-outlined spin /></span>
                </div>
            </a-form-item>

            <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
                <a-button :disabled="disabled" type="primary" html-type="submit" class="login-button">
                    注册
                </a-button>
            </a-form-item>

            <div class="right">
                <br />
                <span>已有账户</span>
                &nbsp;&nbsp;
                <span class="font" @click="login">登录</span>
            </div>
        </a-form>
     </el-card>
    </div>
  <Footer />
</template>

<script>
import { defineComponent, reactive, ref, computed } from 'vue';
import { UserOutlined, LockOutlined, CheckCircleOutlined, SyncOutlined, PhoneOutlined } from '@ant-design/icons-vue';
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import icon_img from "../static/2.gif";
import SIdentify from "@/components/verify.vue";
import { mapActions } from 'vuex';
import { message } from 'ant-design-vue';

export default defineComponent({
  components: {
    Header, 
    Footer,
    UserOutlined,
    LockOutlined,
    CheckCircleOutlined,
    SyncOutlined,
    PhoneOutlined,
    SIdentify,
  },

  setup() {
    
    const layout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 14,
      },
    };
   
    return {
      icon_img,
      background_image:"https://images.pexels.com/photos/785418/pexels-photo-785418.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      layout,
    };
  },

  
  data(){
    let usernamevalidator = async (_rule, value) => {
      if (value ===''){
        return Promise.reject('请输入昵称');
      }else if (value.length<2) {
          return Promise.reject('昵称在 2 到 10 个字符');
      } else if (value.length>10){
          return Promise.reject('昵称在 2 到 10 个字符');
      } else{
        return Promise.resolve();
      }
    };

    let telephonevalidator = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入手机号');
      }
      if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        return Promise.reject('手机号格式错误');
      } else {
          return Promise.resolve();
        }
    };

    let validatePass = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入密码');
      } else if (value.length<6) {
          return Promise.reject('密码必须大于6位');
      } else if (value.length>20){
          return Promise.reject('密码必须小于20位');
      } else{
        return Promise.resolve();
      }
    };

    let validatePass2 = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入密码');
      } else if (value !== this.formState.password) {
          return Promise.reject('两次输入密码不一致!');
      } else{
        return Promise.resolve();
      }
    };
    
    let validateVerifycode = async (_rule, value) => {
        if (value === '') {
        return Promise.reject('请输入验证码');
      } else if (value !== this.identifyCode){
        return Promise.reject('验证码不正确');
      } else{
        return Promise.resolve();
      }
    };

    const rules = {
      name:[{
        required: true,
        validator: usernamevalidator,
        trigger: 'change',
      }],
      telephone: [{
        required: true,
        validator: telephonevalidator,
        trigger: 'change',
      }],
      password: [{
        required: true,
        validator: validatePass,
        trigger: 'change',
      }],
      password2: [{
        required: true,
        validator: validatePass2,
        trigger: 'change',
      }],
      verifycode: [{
        required: true,
        validator: validateVerifycode,
        trigger: 'change',
      }],
    };

    const formRef = ref();
    const formState = reactive({
      name:'',
      telephone: '',
      password: '',
      password2:'',
      verifycode: '',
    });

    const disabled = computed(() => {
      return !(formState.name&&formState.telephone && formState.password);
    });

    const handleFinish = values => {
      console.log(values, formState);
      this.userRegister({
        name:this.formState.name,
        telephone:this.formState.telephone,
        password:this.formState.password,
      }).then(() => {
        message.success('注册成功',2.5);
        this.$router.push({ name: "Home" });
      }).catch((err) => {
        if(err.response.status==422){
          message.error('注册失败，该手机号已被注册',2.5);
        }else{
          message.error('系统异常，请稍后再试',2.5);
        }
      })
    };

    const handleFinishFailed = errors => {
      message.warning('验证码错误',2.5);
    };


    const handleValidate = (...args) => {
      // console.log(args);
    };
    

    return{
        rules,
        identifyCodes: '1234567890',
	      identifyCode: '',
        formState,
        formRef,
        disabled,
        handleFinish,
        handleFinishFailed,
        handleValidate,
    }
  },

  mounted() {
    // 验证码初始化
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },

  methods: {
    ...mapActions('userModule', { userRegister: 'register' }),
    randomNum(min, max) {
        return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
        this.identifyCode = ''
        this.makeCode(this.identifyCodes, 4)
    },
    makeCode(o, l) {
        for (let i = 0; i < l; i++) {
            this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
        }
    },
    login(){
      this.$router.push({ name: "Login" });
    },
    
  }


});
</script>

<style scoped>
#card{
    display:flex;
    justify-content: center;
    align-items: center;
    position:relative;
    width: 100%;
    height: 100vh;
    background-size: cover;
}

.box-card {
  width: 500px;
}

.icon-card{
  display:flex;
  justify-content: center;
  align-items: center;
  position:relative;
}
#login-title{
  font-size: large;
  font-weight: 800;
  align-self:center;
}
.identifybox {
  display: flex;
  justify-content: center;
}
.text{
  display:flex;
  padding-left: 10px;
  padding-top: 20px;
  color: black;
  text-decoration: none;
  font-family: "Verdana";
  font-weight: 500;
  font-style: normal;
  cursor: pointer;
}
.text:hover{
  color: lightskyblue;
}
.login-button{
  text-align: center;
  height: 35px;
  
  border-radius: 5px;
  width: 200px;
}
/* .login-button:hover {
  background: lightskyblue;
} */
.right{
  padding-top: 30px;
  display:flex;
  justify-content: right;
}
.font{
  color: lightskyblue;
  font-weight: 800;
  cursor: pointer;
}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-wrap {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
#components-form-demo-normal-login .login-form-forgot {
  margin-bottom: 24px;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
</style>
